<?php
/**
 * +-------------------------------------------------------------
 * |Caption:
 * +-------------------------------------------------------------
 * |Author: Lenny
 * +-------------------------------------------------------------
 * |Email:  1685964109@qq.com
 * +-------------------------------------------------------------
 * |Date:   2024/6/18 上午10:07
 * +-------------------------------------------------------------
 */

namespace app\admin\controller;

use app\admin\model\SysAuth;
use app\admin\model\SysAuthMenu;
use app\admin\validate\SysAuthValidate;
use app\common\controller\AdminController;
use app\Request;
use Exception;
use think\App;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\response\Json;
use app\admin\service\annotation\ControllerAnnotation;
use app\admin\service\annotation\NodeAnnotation;

/**
 * @ControllerAnnotation (title="角色权限管理")
 */
class Auth extends AdminController
{
    protected array $sort = [
            'sort' => 'desc',
            'id'   => 'desc',
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new SysAuth();
        $this->validateClass = SysAuthValidate::class;
    }

    /**
     * @NodeAnnotation (title="角色权限列表")
     * @param Request $request
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function saveAuthorize(Request $request): Json
    {
        if(!$request->isPost()) return $this->errorJson('当前请求不合法!');
        $post = $request->post();
        $row  = $this->model->find($post['id']);
        if(!$row) return $this->errorJson('数据不存在!');
        $node = $request->post('node', "");
        try {
            //删除历史权限
            $authNode = new SysAuthMenu();
            $authNode->delHistoryAuthNode($row['id']);
            if($node) {
                $node = explode(',', $node);
                $saveAll = [];
                foreach($node as $vo) {
                    $saveAll[] = [
                            'auth_id' => $row['id'],
                            'menu_id' => $vo,
                    ];
                }
                $authNode->saveAll($saveAll);
            }
            // 更新菜单
        }catch(Exception $e){
            return $this->errorJson('保存失败:'.$e->getMessage());
        }
        return $this->successJson('保存成功!');
    }
}